package com.ess.utils;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * 日期时间处理工具类
 *
 * @author tangyulong
 * @version V1.0
 * @ClassName: DateUtils
 * @date 2017年12月20日 下午12:47:07
 */
public class DateUtils {

	/**
	 * @Fields 日期格式yyyy-MM-dd
	 */
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
	/**
	 * @Fields 日期格式yyyy-MM-dd HH:mm:ss
	 */
	public static final String DATE_FORMAT_DATE_TIME = "yyyy-MM-dd HH:mm:ss";
	/**
	 * @Fields 日期格式yyyyMMddHHmmss
	 */
	public static final String DATE_FORMAT_DATE_TIME1 = "yyyyMMddHHmmss";

	/**
	 * @Fields DATE_FORMAT_DATE_TIME2 : 日期格式yyyyMMdd
	 */
	public static final String DATE_FORMAT_DATE_TIME2 = "yyyyMMdd";

	/**
	 * date转String
	 *
	 * @param date
	 * @param format 转换格式,例:yyyy-MM-dd HH:mm:ss
	 */
	public static String dateToString(Date date, String format) {
		if (StringUtils.isBlank(format)) {
			format = DATE_FORMAT_DATE_TIME;
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}

	/**
	 * String转date
	 *
	 * @param date
	 * @param format 转换格式,例:yyyy-MM-dd HH:mm:ss
	 */
	public static Date stringToDate(String date, String format) {
		if (StringUtils.isBlank(format)) {
			format = DATE_FORMAT_DATE_TIME;
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		try {
			return dateFormat.parse(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 获得某天最大时间 2017-10-15 23:59:59
	public static Date getEndOfDay(Date date) {
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
		;
		LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
		return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
	}

	// 获得某天最小时间 2017-10-15 00:00:00
	public static Date getStartOfDay(Date date) {
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
		LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
		return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
	}

	public static Date DateConvert(Date date, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		if (date != null) {
			String s = sdf.format(date);
			try {
				return sdf.parse(s);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
